import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import api from './api';
import type { Snippet } from './snippetTypes';

function SnippetForm() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const isEdit = Boolean(id);
  const [title, setTitle] = useState('');
  const [code, setCode] = useState('');
  const [loading, setLoading] = useState(isEdit);
  const [error, setError] = useState('');

  useEffect(() => {
    if (isEdit) {
      const fetchSnippet = async () => {
        try {
          const response = await api.get<Snippet>(`/snippets/${id}`);
          setTitle(response.data.title);
          setCode(response.data.code);
          setLoading(false);
        } catch (error) {
          setError('获取代码失败');
          setLoading(false);
        }
      };
      fetchSnippet();
    }
  }, [id, isEdit]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      if (isEdit) {
        await api.put(`/snippets/${id}`, { title, code });
      } else {
        await api.post('/snippets', { title, code });
      }
      navigate('/snippets');
    } catch (err) {
      setError('保存失败');
    }
  };

  if (loading) return <div>加载中...</div>;

  return (
    <div className="snippet-form">
      <h2>{isEdit ? '编辑代码片段' : '新建代码片段'}</h2>
      {error && <div className="error">{error}</div>}
      <form onSubmit={handleSubmit}>
        <div className="form-group">
          <label>标题</label>
          <input type="text" value={title} onChange={e => setTitle(e.target.value)} required />
        </div>
        <div className="form-group">
          <label>代码</label>
          <textarea value={code} onChange={e => setCode(e.target.value)} required />
        </div>
        <button className="btn" type="submit">{isEdit ? '保存修改' : '创建'}</button>
      </form>
    </div>
  );
}

export default SnippetForm;